# -*- coding: utf-8 -*-
"""
Created on Sun Jun 20 09:38:02 2021

@author: Wenqing Zhou (zhou.wenqing@qq.com)
@github: https://github.com/ouening
"""
# 参考链接：
# （1）https://www.cnblogs.com/chenpingzhao/p/11383856.html
# （2）https://www.emqx.cn/blog/how-to-use-mqtt-in-python
# （3）https://www.dtmao.cc/news_show_759697.shtml
import random,json
import time
import datetime
from paho.mqtt import client as mqtt_client

## ===========方法1===========
# 使用mosquitto服务端程序创建本地的mqtt服务，需要配置mosquitto.conf文件，
# 可以参考https://www.dtmao.cc/news_show_759697.shtml，此时host是127.0.0.1，或者是通过ipconfig（windows）查看本机ip地址
broker = '127.0.0.1'

## ==========方法2============
# 笔者在腾讯云有个带公网ip的ubuntu服务器，通过ppa安装好mosquitto之后，修改conf配置文件，
# 创建用户，重启mosquitto服务
# broker = '服务器ip地址' # 使用公网服务器ip地址

## ==========方法3============
# 使用物联网厂商提供的公共服务器或者私有服务器进行连接，可以参考https://www.emqx.cn/blog/how-to-use-mqtt-in-python
broker = 'yigrow.cn'
port = 5872
username = 'shhooserver001'
passwd = 'shhoo2018'

broker = '127.0.0.1'
port = 9999
username = ''
passwd = ''


topic = "topicbase/413e63f7e0dd5381fdbb324bf048068ab206dd06ea8885c7a71f137832dfd9a8/test"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'

# 连接mqtt服务器
def connect_mqtt():
    def on_exec(strcmd):
        print ("Exec:",strcmd)
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)
    def on_publish(mqttc, obj, mid):
        print("OnPublish, mid: "+str(mid))
 
    def on_subscribe(mqttc, obj, mid, granted_qos):
        print("Subscribed: "+str(mid)+" "+str(granted_qos))
     
    def on_log(mqttc, obj, level, string):
        print("Log:"+string)
     
    def on_message(mqttc, obj, msg):
        curtime = datetime.datetime.now()
        strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
        print(strcurtime + ": " + msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
        on_exec(str(msg.payload))

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password=passwd)
    print('链接',client)
    client.on_connect = on_connect
    client.on_log = on_log
    client.on_message = on_message

    # 连接mqtt服务器
    # client.username_pw_set(username, password=passwd)
    client.connect(broker, port)

    return client


def publish(client):
    msg_count = 0
    while True:
        print('start')
        time.sleep(1)
        msg = {
            'count':1,
            'type': 1,
            'msg': random.randint(0, 100),
            'time': time.strftime('%Y-%m-%d %H:%M:%S')
        }
        result=client.publish(topic=topic, payload=json.dumps(msg), retain=False)
        # result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"发布 `{msg}` 到 `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        
        time.sleep(5)
        msg_count += 1


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()
